﻿package com.jfdesgagne.traklib.utils {
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.getTimer;

	public class FPS extends TextField {
		private var _fs: int;
		private var _ms: int;
		
		public function FPS() {
			var format: TextFormat = new TextFormat();
				format.color = 0x000000;
				format.size = 10;
				format.bold = true;
				format.font = 'Verdana';
			

			this.autoSize = "left";
			this.defaultTextFormat = format;
			this.background = true;
			this.backgroundColor = 0xffffff;
			
			this._ms = getTimer();
			this._fs = 0;
			
			this.addEventListener(Event.ADDED, this.onAdded);	
			this.addEventListener(Event.REMOVED, this.onRemoved);
		}
		
		private function onAdded(event:Event):void {
			stage.addEventListener(Event.ENTER_FRAME, this.displayFPS);
		}
		
		private function onRemoved(event:Event): void {
			stage.removeEventListener(Event.ENTER_FRAME, this.displayFPS);
		}
		
		private function displayFPS(event:Event):void {
			if(getTimer() - 1000 >this._ms){
				this._ms = getTimer();
				this.text = this._fs.toString();
				this._fs = 0;
			} else this._fs++;

		}
	}
}